canvas下雪背景 html+css+js

您所在的位置:网站首页 canvas 背景音乐 canvas下雪背景 html+css+js

canvas下雪背景 html+css+js

2023-08-26 23:07| 来源: 网络整理| 查看: 265

先看效果:

在这里插入图片描述

实现:

1. 定义标签:

北极光之夜。

h1是标题,.bg是背景图,canvas是画布。

2. 开始js部分,先获取画布:

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d");

3.定义常量与数组,看注释:

/* 定义x为窗口宽度,y为窗口高度 */ var x = 0 ,y=0; /* 定义数组,是为了存储每一片雪的信息 */ var arr=[]; /* 假设有600片雪 */ var num=600;

4.初始化数组,给每片雪花定义随机位置坐标(x,y)与半径(r)与一个颜色(color):

for(let i=0;i x: x*Math.random(), y: y*Math.random(), r: Math.random()*5, color:`rgba(255,255,255,${Math.random()})` }) }

Math.random()会返回0到1间的一个随机数。

5.绘制每片雪与雪花:

/* 创建image元素 */ var img = new Image(); /* 设置雪花的地址,只有雪花是用图片表示 */ img.src = "img/snow.png"; function draw(){ /* 遍历数组 */ for(let i=0;i /* 绘制雪花图片 */ ctx.drawImage(img,yuan.x,yuan.y,yuan.r*10,yuan.r*10); } /* 填充路径 */ ctx.fill(); } }

6.更新雪的位置:

function updated() { for(let i=0;i /* 重新给雪数组赋值 */ arr[i]={ x: x*Math.random(), y: -10, r: Math.random()*5, color:`rgba(255,255,255,${Math.random()})`} } } }

7.设置动画:

setInterval(function(){ /* 清屏 */ ctx.clearRect(0,0,x,y); /* 绘制 */ draw(); /* 更新 */ updated(); },10)

8.完善,让x与y自适应窗口宽度,调用下面函数便可:

/* 绑定窗口大小发生改变事件,让canvas随时铺满浏览器可视区 */ window.onresize=resizeCanvas; function resizeCanvas(){ x=canvas.width=window.innerWidth; y=canvas.height=window.innerHeight; } resizeCanvas(); 完整代码: Document *{ margin: 0; padding: 0; box-sizing: border-box; } body{ height: 100vh; } .bg{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: url(img/52.jpg); background-size: cover; z-index: -10; } h1{ position: absolute; top: 50%; left: 50%; transform: translate(-42%,-50%); font-family: 'fangsong'; font-size: 6em; color: rgba(255, 255, 255, 0.5); text-shadow: 0 0 10px rgb(255,255,255); } 北极光之夜。 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); /* 定义x为窗口宽度,y为窗口高度 */ var x = 0 ,y=0; /* 定义数组,是为了存储每一片雪与雪花的信息 */ var arr=[]; /* 假设有600片雪 */ var num=600; /* 绑定窗口大小发生改变事件,让canvas随时铺满浏览器可视区 */ window.onresize=resizeCanvas; function resizeCanvas(){ x=canvas.width=window.innerWidth; y=canvas.height=window.innerHeight; } resizeCanvas(); for(let i=0;i x: x*Math.random(), y: y*Math.random(), r: Math.random()*5, color:`rgba(255,255,255,${Math.random()})` }) } /* 创建image元素 */ var img = new Image(); /* 设置雪花的地址,只有雪花是用图片表示 */ img.src = "img/snow.png"; function draw(){ /* 遍历数组 */ for(let i=0;i /* 绘制雪花图片 */ ctx.drawImage(img,yuan.x,yuan.y,yuan.r*10,yuan.r*10); } /* 填充路径 */ ctx.fill(); } } function updated() { for(let i=0;i /* 重新给雪数组赋值 */ arr[i]={ x: x*Math.random(), y: -10, r: Math.random()*5, color:`rgba(255,255,255,${Math.random()})`} } } } setInterval(function(){ /* 清屏 */ ctx.clearRect(0,0,x,y); /* 绘制 */ draw(); /* 更新 */ updated(); },10) 总结:

canvas我也是在初学,有不对地方请大佬指正~~



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3